#include "Comm.hpp"
#include "Fifo.hpp"

// int work()
// {

//     // 创建key
//     key_t key = ftok("/home/lw/storehouse/process_communication", 0x66);
//     printf("%d\n", key);

//     // 创建共享内存
//     int shmid = shmget(key, 4096, IPC_CREAT | 0666);
//     if(shmid < 0)
//     {
//         printf("shmget fail, errno is %d, errstr is %s\n", errno, strerror(errno));
//         return errno;
//     }
//     printf("shmget success, shmid = %d\n", shmid);

//     // 挂接上共享区
//     char* shmaddr = (char*)shmat(shmid, nullptr, 0);
//     if((long)shmaddr == -1)
//     {
//         printf("shmat fail, errno is %d, errstr is %s\n", errno, strerror(errno));
//         return errno;
//     }
//     printf("shmat success\n");


//     // client 写数据, 从A写到Z
//     memset(shmaddr, 0, 4096);
//     for(char ch = 'A'; ch <= 'Z'; ++ch)
//     {
//         shmaddr[ch-'A'] = ch;
//     }
//     sleep(2);

//     // 去挂接
//     shmdt(shmaddr);
//     printf("去挂接成功\n");
    
// }


int main()
{
    Sync syn;

    int wfd = syn.OpenWR();

    key_t key = GetKey();
    cout << "成功创建key, key = " << ItoH(key) << endl;
    const int size = 4096;
    sleep(2);

    int shmid = GetShm(key, size);
    cout << "成功获得共享内存" << endl;
    sleep(2);

    char* shmaddr = (char*)ShmAttach(shmid);
    cout << "成功挂接共享内存" << endl;
    sleep(2);

    // 写
    string str = "I am Process1";
    memcpy(shmaddr, str.c_str(), str.size());
    syn.WakeUp(wfd);

    ShmDetach((void*)shmaddr);
    cout << "成功去挂接共享内存" << endl;
    sleep(2);

    syn.Close(wfd);
    return 0;
}